import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';
import 'rxjs/add/operator/toPromise';

import { Term } from '../components/Interfaces/Term';

const httpOptions = {
  headers: new Headers({
    'Content-Type': 'application/json',
  })
};

@Injectable()
export class TermService {

    private termsUrl = '/api/v1/terms';  // URL to web api

    constructor(
        private http: Http,
    ) { }

    getTerms () :Promise<Term[]>{
        return this.http.get(this.termsUrl)
        .toPromise()
        .then(response => response.json().data as Term[])
        .catch(this.handleError);
    }
    // getTerms () :Observable<Term[]>{
    //     return this.http.get(this.termsUrl)
    //         .map(response => response.json())
    // }

  /** POST: add a new Term to the server */
    addTerm (term: Term) :Observable<any>{
        return this.http.post (this.termsUrl, term, httpOptions).map(res => res.json());
    }

    editTerm (term: Term) {
        return this.http.put( this.termsUrl+'/'+term.id,term,httpOptions)
            .toPromise()
            .then(response => response.json())
            .catch(this.handleError);
    }


    delete(term: Term){
        return this.http.delete(this.termsUrl+'/'+term.id,httpOptions)
            .toPromise()
            .then(response => response.json())
            .catch(this.handleError);
    }
    /**
     * Handle Http operation that failed.
     * Let the app continue.
     * @param operation - name of the operation that failed
     * @param result - optional value to return as the observable result
     */
    private handleError (error: any ): Promise<any> {
        console.error('An error occurred', error); // for demo purposes only
        return Promise.reject(error.status || error);
    }

    /** Log a HeroService message with the MessageService */
    private log(message: string) {
        console.log('TermService: ' + message);
    }
}
